from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import Menus


class MenuSerializers(ModelSerializer):
    pid = serializers.SerializerMethodField()
    menu_pid = serializers.IntegerField(write_only=True)
    type = serializers.IntegerField()
    created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = Menus
        fields = ["id", "name", "is_show", "orders", "icon", "type", "api_path", "path", "type", "method", "identical",
                  "description", "pid", "created_at", "updated_at", "menu_pid"]
        read_only_fields = ["id", "created_at", "updated_at"]
        extra_kwargs = {
            "orders": {"required": False},
            "description": {"required": False},
            "is_show": {"required": False}
        }

    def get_pid(self, obj):
        if obj.parent:
            return obj.parent.id
        return 0

    def validate(self, attrs):
        menu_type = attrs.get("type")
        icon = attrs.get("icon")
        if menu_type == 2 and not icon:
            raise ValidationError("类型为菜单时图标不能为空")
        elif menu_type == 1 and icon:
            raise ValidationError("类型为按钮类型是不能存在图标")
        return attrs

    def validate_menu_pid(self, item):
        menu_obj = Menus.objects.filter(id=item).first()
        if not menu_obj:
            raise ValidationError(f"id以{item}的菜单不存在")
        return item
